<template>
  <div class="user-management-page">
    <div class="page-header">
      <h1>用户权限管理</h1>
      <p>管理系统用户和菜单权限配置</p>
    </div>

    <!-- 用户统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#409EFF"><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#67C23A"><Crown /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.adminUsers }}</div>
              <div class="stat-label">管理员</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24" color="#E6A23C"><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.activeUsers }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户列表</span>
              <div>
                <el-button type="primary" @click="showPermissionDialog">
                  <el-icon><Setting /></el-icon>
                  菜单权限配置
                </el-button>
                <el-button type="success" @click="initDefaultMenus">
                  <el-icon><Plus /></el-icon>
                  初始化默认菜单
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table 
            :data="userList" 
            v-loading="loading"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="username" label="用户名" min-width="100" />
            <el-table-column prop="full_name" label="姓名" min-width="100" />
            <el-table-column prop="email" label="邮箱" min-width="200" />
            <el-table-column label="角色" min-width="90">
              <template #default="{ row }">
                <el-tag :type="row.is_admin ? 'danger' : 'primary'">
                  {{ row.is_admin ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width="80">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'info'">
                  {{ row.is_active ? '激活' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="last_login" label="最后登录" min-width="160">
              <template #default="{ row }">
                {{ row.last_login ? formatTime(row.last_login) : '从未登录' }}
              </template>
            </el-table-column>
            <el-table-column label="统计数据" min-width="400">
              <template #default="{ row }">
                <div class="user-stats">
                  <span class="stat-item">分析: {{ row.stats?.analysis_count || 0 }}</span>
                  <span class="stat-item">生成: {{ row.stats?.test_case_generation_count || 0 }}</span>
                  <span class="stat-item">需求: {{ row.stats?.requirements_count || 0 }}</span>
                  <span class="stat-item">用例: {{ row.stats?.test_cases_count || 0 }}</span>
                  <span class="stat-item">UI脚本: {{ row.stats?.ui_scripts_count || 0 }}</span>
                  <span class="stat-item">接口: {{ row.stats?.api_interfaces_count || 0 }}</span>
                  <span class="stat-item">场景: {{ row.stats?.scenarios_count || 0 }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="editUserPermissions(row)"
                >
                  权限设置
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="用户权限设置"
      width="800px"
      :before-close="handleClosePermissionDialog"
      class="permission-dialog"
    >
      <div v-if="selectedUser">
        <div class="user-info-horizontal">
          <h4 class="section-title">用户信息</h4>
          <div class="user-details">
            <span class="user-item">用户名: {{ selectedUser.username }}</span>
            <span class="user-item">姓名: {{ selectedUser.full_name }}</span>
            <span class="user-item">角色: {{ selectedUser.is_admin ? '管理员' : '普通用户' }}</span>
            <span class="user-item">邮箱: {{ selectedUser.email }}</span>
          </div>
        </div>

        <div class="permission-config">
          <h4 class="section-title">菜单权限配置</h4>
          <el-table :data="menuPermissions" border style="width: 100%; font-size: 13px;">
            <el-table-column prop="menu_name" label="菜单名称" min-width="120" />
            <el-table-column prop="required_role" label="默认权限" min-width="100">
              <template #default="{ row }">
                <el-tag :type="row.required_role === 'admin' ? 'danger' : 'primary'" size="small">
                  {{ row.required_role === 'admin' ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="当前权限" min-width="100">
              <template #default="{ row }">
                <el-tag 
                  :type="getPermissionStatus(row) === '允许' ? 'success' : 
                         getPermissionStatus(row) === '禁止' ? 'danger' : 'info'" 
                  size="small"
                >
                  {{ getPermissionStatus(row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="权限设置" min-width="200">
              <template #default="{ row }">
                <el-radio-group 
                  v-model="row.is_granted" 
                  size="small"
                  @change="onPermissionChange(row)"
                >
                  <el-radio :value="true">允许</el-radio>
                  <el-radio :value="false">禁止</el-radio>
                  <el-radio :value="null">默认</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClosePermissionDialog">取消</el-button>
          <el-button type="primary" @click="saveUserPermissions" :loading="saving">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 菜单权限配置对话框 -->
    <el-dialog
      v-model="menuConfigDialogVisible"
      title="菜单权限配置"
      width="900px"
      :before-close="handleCloseMenuDialog"
    >
      <div class="menu-config">
        <div class="config-header">
          <h4>系统菜单配置</h4>
          <el-button type="success" @click="initDefaultMenus">
            <el-icon><Plus /></el-icon>
            初始化默认菜单
          </el-button>
        </div>

        <el-table :data="allMenus" border style="width: 100%" v-loading="loadingMenus">
          <el-table-column prop="menu_key" label="菜单标识" width="120" />
          <el-table-column prop="menu_name" label="菜单名称" width="120" />
          <el-table-column prop="menu_path" label="路径" width="150" />
          <el-table-column prop="icon" label="图标" width="80">
            <template #default="{ row }">
              <el-icon v-if="row.icon">
                <component :is="row.icon" />
              </el-icon>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="sort_order" label="排序" width="80" />
          <el-table-column prop="required_role" label="所需角色" width="100">
            <template #default="{ row }">
              <el-tag :type="row.required_role === 'admin' ? 'danger' : 'primary'" size="small">
                {{ row.required_role === 'admin' ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.is_active"
                @change="updateMenuStatus(row)"
                :loading="row.updating"
              />
            </template>
          </el-table-column>
          <el-table-column label="可见性" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.is_visible"
                @change="updateMenuVisibility(row)"
                :loading="row.updating"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <div style="display: flex; gap: 8px; flex-wrap: nowrap;">
                <el-button size="small" type="primary" @click="editMenu(row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="deleteMenu(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseMenuDialog">关闭</el-button>
          <el-button type="primary" @click="refreshMenus">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑菜单对话框 -->
    <el-dialog
      v-model="editMenuDialogVisible"
      title="编辑菜单"
      width="600px"
    >
      <el-form :model="editingMenu" label-width="100px" v-if="editingMenu">
        <el-form-item label="菜单标识">
          <el-input v-model="editingMenu.menu_key" placeholder="如: dashboard" />
        </el-form-item>
        <el-form-item label="菜单名称">
          <el-input v-model="editingMenu.menu_name" placeholder="如: 仪表盘" />
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input v-model="editingMenu.menu_path" placeholder="如: /dashboard" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="editingMenu.icon" placeholder="如: DataBoard" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editingMenu.sort_order" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="所需角色">
          <el-select v-model="editingMenu.required_role">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editingMenu.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editMenuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMenu" :loading="savingMenu">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import { ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { dashboardApi } from '@/api/dashboard'
import request from '@/utils/request'

const router = useRouter()
const toast = useToast()

// 数据状态
const loading = ref(false)
const saving = ref(false)
const userList = ref([])
const userStats = ref({
  totalUsers: 0,
  adminUsers: 0,
  activeUsers: 0
})

// 对话框状态
const permissionDialogVisible = ref(false)
const menuConfigDialogVisible = ref(false)
const editMenuDialogVisible = ref(false)

// 选中的用户和权限数据
const selectedUser = ref(null)
const menuPermissions = ref([])

// 菜单配置相关数据
const loadingMenus = ref(false)
const savingMenu = ref(false)
const allMenus = ref([])
const editingMenu = ref(null)

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 加载用户统计数据
const loadUserStats = async () => {
  try {
    const response = await dashboardApi.getUserStats()
    console.log('User stats API response:', response)
    if (response && response.data) {
      // 检查数据结构
      let users = []
      if (response.data.success && response.data.data && response.data.data.users) {
        users = response.data.data.users
      } else if (response.data.users) {
        users = response.data.users
      } else {
        console.warn('未找到用户数据，数据结构:', response.data)
        users = []
      }
      
      userList.value = users
      
      userStats.value = {
        totalUsers: users.length,
        adminUsers: users.filter(u => u.is_admin).length,
        activeUsers: users.filter(u => u.is_active).length
      }
    }
  } catch (error) {
    console.error('加载用户统计数据失败:', error)
    toast.error('加载用户数据失败')
  }
}

// 编辑用户权限
const editUserPermissions = async (user) => {
  selectedUser.value = user
  loading.value = true
  
  try {
    const response = await request({
      url: `/api/v1/menu/admin/user-permissions/${user.user_id}`,
      method: 'get'
    })
    
    if (response && response.data) {
      if (response.data.success && response.data.data) {
        menuPermissions.value = response.data.data.menu_permissions
      } else {
        menuPermissions.value = response.data.menu_permissions || []
      }
      permissionDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取用户权限失败:', error)
    toast.error('获取用户权限失败')
  } finally {
    loading.value = false
  }
}

// 获取权限状态显示
const getPermissionStatus = (row) => {
  if (row.is_granted === null) {
    return row.default_access ? '默认允许' : '默认禁止'
  }
  return row.is_granted ? '允许' : '禁止'
}

// 权限变更处理
const onPermissionChange = (row) => {
  // 可以在这里添加实时预览逻辑
}

// 保存用户权限
const saveUserPermissions = async () => {
  if (!selectedUser.value) return
  
  saving.value = true
  
  try {
    await request({
      url: `/api/v1/menu/admin/user-permissions/${selectedUser.value.user_id}`,
      method: 'post',
      data: {
        menu_permissions: menuPermissions.value
      }
    })
    
    toast.success('用户权限保存成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('保存用户权限失败:', error)
    toast.error('保存用户权限失败')
  } finally {
    saving.value = false
  }
}

// 关闭权限对话框
const handleClosePermissionDialog = () => {
  permissionDialogVisible.value = false
  selectedUser.value = null
  menuPermissions.value = []
}

// 显示菜单配置对话框
const showPermissionDialog = async () => {
  menuConfigDialogVisible.value = true
  await loadAllMenus()
}

// 加载所有菜单配置
const loadAllMenus = async () => {
  loadingMenus.value = true
  try {
    const response = await request({
      url: '/api/v1/menu/admin/menus',
      method: 'get'
    })
    
    if (response && response.data && response.data.success) {
      allMenus.value = response.data.data.menus.map(menu => ({
        ...menu,
        updating: false // 添加更新状态标记
      }))
    }
  } catch (error) {
    console.error('加载菜单配置失败:', error)
    toast.error('加载菜单配置失败')
  } finally {
    loadingMenus.value = false
  }
}

// 初始化默认菜单
const initDefaultMenus = async () => {
  try {
    await request({
      url: '/api/v1/menu/admin/init-default-menus',
      method: 'post'
    })
    
    toast.success('默认菜单初始化成功')
    await loadAllMenus() // 重新加载菜单列表
  } catch (error) {
    console.error('初始化默认菜单失败:', error)
    toast.error('初始化默认菜单失败')
  }
}

// 更新菜单状态
const updateMenuStatus = async (menu) => {
  menu.updating = true
  try {
    await request({
      url: `/api/v1/menu/admin/menus/${menu.id}`,
      method: 'put',
      data: {
        is_active: menu.is_active
      }
    })
    
    toast.success('菜单状态更新成功')
  } catch (error) {
    console.error('更新菜单状态失败:', error)
    toast.error('更新菜单状态失败')
    // 回滚状态
    menu.is_active = !menu.is_active
  } finally {
    menu.updating = false
  }
}

// 更新菜单可见性
const updateMenuVisibility = async (menu) => {
  menu.updating = true
  try {
    await request({
      url: `/api/v1/menu/admin/menus/${menu.id}`,
      method: 'put',
      data: {
        is_visible: menu.is_visible
      }
    })
    
    toast.success('菜单可见性更新成功')
  } catch (error) {
    console.error('更新菜单可见性失败:', error)
    toast.error('更新菜单可见性失败')
    // 回滚状态
    menu.is_visible = !menu.is_visible
  } finally {
    menu.updating = false
  }
}

// 编辑菜单
const editMenu = (menu) => {
  editingMenu.value = { ...menu }
  editMenuDialogVisible.value = true
}

// 保存菜单
const saveMenu = async () => {
  if (!editingMenu.value) return
  
  savingMenu.value = true
  try {
    await request({
      url: `/api/v1/menu/admin/menus/${editingMenu.value.id}`,
      method: 'put',
      data: editingMenu.value
    })
    
    toast.success('菜单保存成功')
    editMenuDialogVisible.value = false
    await loadAllMenus() // 重新加载菜单列表
  } catch (error) {
    console.error('保存菜单失败:', error)
    toast.error('保存菜单失败')
  } finally {
    savingMenu.value = false
  }
}

// 删除菜单
const deleteMenu = async (menu) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.menu_name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await request({
      url: `/api/v1/menu/admin/menus/${menu.id}`,
      method: 'delete'
    })
    
    toast.success('菜单删除成功')
    await loadAllMenus() // 重新加载菜单列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      toast.error('删除菜单失败')
    }
  }
}

// 刷新菜单
const refreshMenus = async () => {
  await loadAllMenus()
}

// 关闭菜单配置对话框
const handleCloseMenuDialog = () => {
  menuConfigDialogVisible.value = false
  allMenus.value = []
}

onMounted(() => {
  loadUserStats()
})
</script>

<style lang="scss" scoped>
.user-management-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  
  h1 {
    margin: 0 0 8px 0;
    color: #303133;
  }
  
  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    padding: 10px;
    
    .stat-icon {
      margin-right: 15px;
      padding: 10px;
      background: #f8f9fa;
      border-radius: 8px;
    }
    
    .stat-info {
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        line-height: 1;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.user-stats {
  .stat-item {
    display: inline-block;
    margin-right: 12px;
    padding: 2px 6px;
    background: #f8f9fa;
    border-radius: 4px;
    font-size: 12px;
    color: #666;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.user-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  
  h4 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 16px;
  }
  
  p {
    margin: 5px 0;
    color: #666;
    font-size: 14px;
  }
}

// 新的横向用户信息布局
.user-info-horizontal {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  
  .section-title {
    margin: 0 0 12px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }
  
  .user-details {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    
    .user-item {
      color: #666;
      font-size: 13px;
      white-space: nowrap;
      
      // 当空间不足时换行
      &:nth-child(n+3) {
        flex-basis: 100%;
      }
      
      @media (min-width: 768px) {
        &:nth-child(n+3) {
          flex-basis: auto;
        }
      }
    }
  }
}

.permission-config {
  h4 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 16px;
  }
  
  .section-title {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }
}

// 权限设置对话框样式
.permission-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 24px;
  }
  
  :deep(.el-table) {
    font-size: 13px;
    
    .el-table__header th {
      font-size: 13px;
      font-weight: 600;
    }
    
    .el-table__body td {
      font-size: 13px;
    }
  }
  
  :deep(.el-radio-group) {
    .el-radio {
      margin-right: 12px;
      
      .el-radio__label {
        font-size: 12px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

.menu-config {
  .config-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h4 {
      margin: 0;
      color: #303133;
      font-size: 16px;
    }
  }
}
</style>